package name.sakanacatcher.service;


import name.sakanacatcher.entity.Com;
import name.sakanacatcher.repository.ComRepository;
import name.sakanacatcher.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

@Service
public class ComService {
    @Autowired
    ComRepository comRepository;

    @Autowired
    RoleService roleService;

    @Autowired
    UserService userService;

    @Autowired
    InformService informService;

    @Autowired
    ResultUtil resultUtil;

    @Autowired
    AuthService authService;

    public ComRepository getComRepository() {
        return comRepository;
    }

    public List<Com> getComTable() {
        List<Com> comList = comRepository.findAll();
        for(Com com:comList){
            if(userService.getPrincipalByCid(com.getId()) != null)
                com.setPrincipal(userService.getPrincipalByCid(com.getId()).getUsername());
        }
        return comList;
    }

    @Transactional
    public boolean updateCom(Map<String,Object> data){
        Com com = parseMapToCom(data);
        Com newCom = comRepository.save(com);
        return comRepository.existsById(newCom.getId());
    }

    public Com parseMapToCom(Map<String,Object> data) {
        Com com = new Com(
            (String) data.get("name"),
            (String) data.get("intro"),
            (String) data.get("logo")
        );
        if (data.containsKey("id") && comRepository.existsById((int)data.get("id"))){
            com.setId((int)data.get("id"));
        }
        return com;
    }

}


